package top.lyf1210.yuwenpicturebackend.utils;

import cn.hutool.json.JSONUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * @ClassNameCacheClient
 * @Description redis缓存客户端
 * @Author钰玟
 * @Date2025/5/11 下午5:07
 * @Version 1.0
 **/
@Component
public class CacheClient {
    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }


    /**
     *
     * @param key 键
     * @param value 值
     * @param time ttl
     * @param unit 单位
     */
    public void set (String key ,Object value , Long time , TimeUnit unit){
        String jsonStrValue = JSONUtil.toJsonStr(value);
        stringRedisTemplate.opsForValue().set(key , jsonStrValue, time , unit);
    }

    /**
     * 设置逻辑过期时间
     * @param key key
     * @param value 值
     * @param time 逻辑过期时间
     * @param unit 时间单位
     */
    public void setWithLogicalExpire (String key ,Object value , Long time, TimeUnit unit ){
        //封装  逻辑过期时间的 对象 Data
//        RedisData data = RedisData.builder().expireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time))).data(value);
        RedisData redisData = new RedisData(LocalDateTime.now().plusSeconds(unit.toSeconds(time)), value);
        String jsonStrValue = JSONUtil.toJsonStr(redisData);
        stringRedisTemplate.opsForValue().set(key , jsonStrValue);
    }


}
